﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI.Controls
{
    public partial class RepairSalesCtrl : BaseEditControl
    {
        const string WHOLESALE = "WHOLESALE";
        const string SALE = "RETAIL";
        const string PARTNER = "PARTNER";

        public bool IsSalePrice
        {
            get 
            {
                if (ViewState["IsSalePrice"] == null)
                    ViewState["IsSalePrice"] = true;
                return (bool)ViewState["IsSalePrice"];
            }
            set { ViewState["IsSalePrice"] = value; }
        }

        public int CustomerPrice
        {
            get
            {
                if (ViewState["CustomerPrice"] == null)
                    ViewState["CustomerPrice"] = CustomerType.CustomerPrice.SalePrice;
                return (int)ViewState["CustomerPrice"];
            }
            set { ViewState["CustomerPrice"] = value; }
        }

        public string GetInvoiceDetailsEditPageLink()
        {
            return this.ResolveUrl("~/EditPages/EditInvoiceDetails.aspx") + "?key=" + invoiceDetails.SourceObjectSessionID;
        }

        public int DefaultCustID
        {
            get { return ViewState["DefaultCustID"] != null ? (int)ViewState["DefaultCustID"] : 0; }
            set{ ViewState["DefaultCustID"] = value;}
        }

        protected void txtVoucherCode_OnTextChanged(object sender, EventArgs e)
        {
            lblVoucher.Text = "";
            View_Vouchers vc = View_Vouchers.GetByCode(txtVoucherCode.Text);
            if (vc.RowCount <= 0)
            {
                ShowErrorMessage(panelVoucher, "Invalid Voucher Code!");
                return;
            }

            if (!vc.Active)
            {
                ShowErrorMessage(panelVoucher, "Voucher Code disabled!");
                return;
            }

            if (vc.IsUsed)
            {
                ShowErrorMessage(panelVoucher, "Voucher Code has been used!");
                return;
            }

            if (vc.IsExpired())
            {
                ShowErrorMessage(panelVoucher, "Voucher Code expired!");
                return;
            }

            if (vc.MultiCheckOut && vc.s_DiscountAmount != "" && vc.s_Balance != "")
                lblVoucher.Text = string.Format("{0:C}", vc.Balance) + " OFF";
            else
                lblVoucher.Text = vc.s_Discount + " OFF";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!SessionUser.EditSales)
            {
                txtDiscountAll.Visible = false;
                btnDiscountAll.Visible = false;
            }

            if (!IsPostBack)
            {
                InvoiceType invType = InvoiceType.GetAllActiveInvoiceType();
                Utilities.LoadDropDownListNoSelect(ddlInvoiceType, invType.DefaultView, InvoiceType.ColumnNames.InvoiceTypeName, InvoiceType.ColumnNames.ID);
                invType.Filter = InvoiceType.ColumnNames.Default + "=1";
                if (invType.RowCount > 0)
                    ddlInvoiceType.SelectedValue = invType.ID.ToString();

                lblStaff.Text = SessionUser.s_FullName;

                //Load for Combobox ACTK
                Customers cust = Customers.GetAllActiveCustomers();
                cust.Sort = Customers.ColumnNames.CustomerName + " asc";
                ddlCustomer.DataTextField = Customers.ColumnNames.CustomerName;
                ddlCustomer.DataValueField = Customers.ColumnNames.ID;
                ddlCustomer.DataSource = cust.DefaultView;
                ddlCustomer.DataBind();
                ListItem defaultCust = new ListItem("Cash Sales", "Sales");
                ddlCustomer.Items.Add(defaultCust);
                ddlCustomer.SelectedValue = DefaultCustID > 0 ? DefaultCustID.ToString() : defaultCust.Value;
                CustomerPrice = CustomerType.CustomerPrice.SalePrice;

                txtDate.Text = DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString(SysVars.DateFormat);

                PaymentMethod methods = PaymentMethod.GetAllMethods();
                Utilities.LoadDropDownList(ddlPaymentMethod, methods.DefaultView, PaymentMethod.ColumnNames.Name, PaymentMethod.ColumnNames.ID);

                NewInvoice();
                
            }
        }

        public void ClearItems()
        {
            invoiceDetails.SourceObject = new InvoiceDetails();
        }

        public void NewInvoice()
        {
            Sequence seq = new Sequence();

            txtInvoiceNo.Text = seq.GetNewID("Invoices");
            
            txtPayAmt.Text = "0";
            txtNote.Text = "";
            txtDiscountAll.Text = "0";
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            invoiceDetails.Refresh();

            txtVoucherCode.Text = "";
            lblVoucher.Text = "";

            RefreshCustPrice();
            btnSubmit.Visible = true;
            btnPrint.Visible = false;

            ddlPaymentMethod.SelectedIndex = 0;
            btnSubmit.Enabled = Branches.CurrentBranchID == SessionUser.BranchID;
        }

        protected void btnDiscountAll_OnClick(object sender, EventArgs e)
        {
            int discount = txtDiscountAll.Text == "" ? 0 : int.Parse(txtDiscountAll.Text);

            invoiceDetails.DiscountAllByPercentage(discount);
        }

        protected void ddlCustomer_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshCustPrice();
            invoiceDetails.AdjustPrice(CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);
        }

        protected void btnEditProd_Click(Object sender, EventArgs e)
        {
            invoiceDetails.UpdateTotalAmt();
            invoiceDetails.Refresh();
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        protected void btnRemoveProd_Click(object sender, EventArgs e)
        {
            invoiceDetails.DeleteCheckedItems();
            invoiceDetails.UpdateTotalAmt();
            invoiceDetails.Refresh();
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        private void RefreshCustPrice()
        {
            int custID;
            try
            {
                custID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                custID = -1;
            }

            View_Customers cust = View_Customers.GetCustomerByID(custID);

            if (cust.RowCount > 0)
            {
                CustomerPrice = cust.Price;
                //IsSalePrice = cust.RowCount <= 0 || cust.DealerPrice == false; //no longer used
                //lblCustPrice.Text = IsSalePrice ? SALE : WHOLESALE;//

                if (cust.Price == CustomerType.CustomerPrice.SalePrice)
                {
                    lblCustPrice.Text = SALE;
                }
                else if (cust.Price == CustomerType.CustomerPrice.DealerPrice)
                    lblCustPrice.Text = WHOLESALE;
                else if (cust.Price == CustomerType.CustomerPrice.PartnerPrice)
                    lblCustPrice.Text = PARTNER;

                if (!cust.IsColumnNull(View_Customers.ColumnNames.CreditLine))
                    lblCustInfo.Text = string.Format("<span class='labelMessage' style='color:{2}'>Bal.: {0:C}    Credit: {1:C}</span>", cust.TotalAmount - cust.PaidAmount, cust.CreditLine, (cust.TotalAmount - cust.PaidAmount > cust.CreditLine) ? "black" : "red");
                else
                    lblCustInfo.Text = string.Format("<span class='labelMessage'>Bal.: {0:C}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Credit:n/a</span>", cust.TotalAmount - cust.PaidAmount);
            }
            else
                lblCustInfo.Text = "";
        }

        protected void ddlCustomer_OnItemInserted(object sender, EventArgs e)
        {
            string cust = ddlCustomer.Text;
            lblCustPrice.Text = SALE;
        }

        public void SetCustomer(int custID)
        {
            int i = ddlCustomer.SelectedIndex;
            try
            {
                ddlCustomer.SelectedValue = custID.ToString();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("RepairSalesCtrl.ascx.cs", "SetCustomer", ex.StackTrace);
                ddlCustomer.SelectedIndex = i;
            }
        }

        public void AddIMEI(string imei)
        {
            invoiceDetails.AddIMEI(imei, CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        public void AddRepair(int jobID)
        {
            invoiceDetails.AddRepair(jobID);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        public void AddProduct(int productID, int quantity)
        {
            invoiceDetails.AddNonIMEIProduct(productID, quantity, CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            if (ddlCustomer.SelectedIndex < 0 || ddlCustomer.Text.Trim() == "")
            {
                ShowErrorMessage(mainPanel, "(*) Please select a customer!");
                return;
            }

            //if (invoiceDetails.TotalAmt == 0)
            //{
            //    ShowErrorMessage(mainPanel, "(*) Nothing to submit!");
            //    return;
            //}

            if (Invoices.IsInvoiceNoExisted(txtInvoiceNo.Text))
            {
                ShowErrorMessage(mainPanel, "(*) Invoice number has already existed!");
                return;
            }

            int customerID = 0;
            try
            {
                customerID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                customerID = 0;
            }

            string oldFilter = "";

            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();
                //step1:create invoice
                Invoices invoice = new Invoices();
                invoice.AddNew();
                invoice.BranchID = Branches.CurrentBranchID;
                invoice.SaleUser = SessionUser.ID;
                invoice.LastModifiedByUser = SessionUser.ID;
                invoice.CreatedByUser = SessionUser.ID;
                invoice.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                invoice.Note = txtNote.Text;
                invoice.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                if (txtPayAmt.Text != "")
                    invoice.PaidAmount = Decimal.Parse(txtPayAmt.Text);
                else
                    invoice.PaidAmount = 0;
                invoice.CustomerName = ddlCustomer.SelectedItem.Text;
                invoice.TotalAmount = invoiceDetails.TotalAmt;
                invoice.GSTTotalAmount = invoiceDetails.TotalGST;
                if (customerID > 0)
                {
                    invoice.CustomerID = customerID;

                    POSSystem.BLL.Customers cust = new POSSystem.BLL.Customers();
                    cust.UpdateCustomerAmt(customerID, invoice.TotalAmount, invoice.PaidAmount);
                }

                if (txtVoucherCode.Text.Trim() != "")
                {
                    string code = txtVoucherCode.Text.Trim();
                    View_Vouchers vc = View_Vouchers.GetByCode(code);
                    if (vc.RowCount >= 0 && vc.Active && !vc.IsUsed && !vc.IsExpired() &&
                        (vc.s_Balance == "" || vc.Balance > 0))
                    {
                        invoice.VoucherID = vc.ID;

                        decimal discountAmt = 0;

                        if (vc.s_DiscountAmount != "")
                        {
                            discountAmt = Math.Min(vc.MultiCheckOut ? vc.Balance : vc.DiscountAmount, invoice.TotalAmount);
                            invoice.TotalAmount -= discountAmt;
                        }
                        else if (vc.s_DiscountPercent != "")
                        {
                            discountAmt = Math.Min(invoice.TotalAmount * vc.DiscountPercent / 100, invoice.TotalAmount);
                            invoice.TotalAmount -= discountAmt;
                        }

                        Vouchers vou = new Vouchers();
                        vou.LoadByPrimaryKey(vc.ID);

                        if (!vc.MultiCheckOut)
                        {
                            vou.IsUsed = true;
                        }
                        else if (vc.s_DiscountAmount != "")
                            vou.Balance -= discountAmt;

                        vou.Save();

                        invoice.SpecialDiscount = discountAmt;
                    }
                    else
                        throw new ApplicationException("Invalid Voucher Code or Balance Exceed!");
                }

                invoice.InvoiceTypeID = int.Parse(ddlInvoiceType.SelectedValue);
                invoice.Deleted = false;
                invoice.InvoiceNo = txtInvoiceNo.Text;

                invoice.InvoiceCategory = (byte)Invoices.InvoiceCategories.Repair;

                invoice.IsRetail = CustomerPrice == CustomerType.CustomerPrice.SalePrice;
                invoice.Save();

                //step2:insert a row into InvoicePaymentHistories if paid Amt > 0
                if (invoice.PaidAmount > 0)
                {
                    InvoicePaymentHistories.AddPaymentHistory(invoice.ID, int.Parse(ddlPaymentMethod.SelectedValue),
                        invoice.PaidAmount, DateTime.Now, SessionUser.ID);
                }

                oldFilter = invoiceDetails.SaleItems.Filter;

                invoiceDetails.SaleItems.Filter = InvoiceDetails.ColumnNames.ItemType + "=" + ((int)(Invoices.InvoiceCategories.Sale)).ToString();
                if (invoiceDetails.SaleItems.RowCount > 0)
                {
                    //step3:add InvoiceDetails
                    InvoiceDetails ivcDetails = new InvoiceDetails();
                    invoiceDetails.SaleItems.Rewind();
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        ivcDetails.AddNew();
                        ivcDetails.BranchID = Branches.CurrentBranchID;
                        String desc = Products.GetProductNameById(invoiceDetails.SaleItems.ProductID);
                        if (!string.IsNullOrEmpty(invoiceDetails.SaleItems.IMEI))
                            desc += string.Format("<br/><span class='hintBold'>IMEI/Serial: {0} </span>", invoiceDetails.SaleItems.IMEI);

                        ivcDetails.AddInfo(invoice.ID, invoiceDetails.SaleItems.ProductID, invoiceDetails.SaleItems.IMEI, invoiceDetails.SaleItems.Quantity,
                            invoiceDetails.SaleItems.GST, invoiceDetails.SaleItems.UnitPrice, invoiceDetails.SaleItems.Discount, invoiceDetails.SaleItems.Cost, desc);
                        ivcDetails.LastModifiedByUser = SessionUser.ID;
                        ivcDetails.s_ItemType = ((int)Invoices.InvoiceCategories.Sale).ToString();
                        invoiceDetails.SaleItems.MoveNext();
                    }
                    ivcDetails.Save();
                    //step4:update ProductDetails status
                    invoiceDetails.SaleItems.Rewind();
                    String imeis = "";
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        if (!String.IsNullOrEmpty(invoiceDetails.SaleItems.IMEI))
                        {
                            imeis += invoiceDetails.SaleItems.IMEI + ",";
                        }

                        invoiceDetails.SaleItems.MoveNext();
                    }
                    if (imeis.EndsWith(","))
                        imeis = imeis.Remove(imeis.Length - 1);
                    if (!String.IsNullOrEmpty(imeis))
                    {
                        ProductDetails prodDetails = ProductDetails.GetProductDetailByIMEIs(imeis);
                        for (int i = 0; i < prodDetails.RowCount; i++)
                        {
                            prodDetails.ProductStatusID = (int)ProductDetails.ProductStatus.Saled;
                            prodDetails.LastModifiedByUser = SessionUser.ID;
                            prodDetails.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                            prodDetails.MoveNext();
                        }
                        prodDetails.Save();

                        //step5:insert into product ProductDetailHistories
                        prodDetails.Rewind();
                        ProductDetailHistories productHistory = new ProductDetailHistories();
                        for (int i = 0; i < prodDetails.RowCount; i++)
                        {
                            invoiceDetails.Filter = "IMEI='" + prodDetails.IMEI + "'";
                            productHistory.AddNew();
                            productHistory.AddInfo(prodDetails.ID, (int)ProductDetails.ProductStatus.Saled,
                                (int)0,
                                String.Format("Saled to {1}. User: '{2}'. Price: {0:C}", invoiceDetails.SaleItems.UnitPrice, invoice.CustomerName, SessionUser.s_FullName),
                                prodDetails.SupplierID, invoiceDetails.SaleItems.UnitPrice);
                            productHistory.UserID = SessionUser.ID;

                            prodDetails.MoveNext();
                        }

                        productHistory.Save();
                    }

                    //step6:update Products Quantity
                    invoiceDetails.SaleItems.Rewind();
                    invoiceDetails.SaleItems.Filter = InvoiceDetails.ColumnNames.ItemType + "=" + ((int)(Invoices.InvoiceCategories.Sale)).ToString();
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        if (String.IsNullOrEmpty(invoiceDetails.SaleItems.IMEI))
                        {
                            //adjust qty, set product.qty += qty
                            String res = Products.UpdateProductQty(invoiceDetails.SaleItems.ProductID, -invoiceDetails.SaleItems.Quantity);
                            if (!string.IsNullOrEmpty(res))
                                throw new Exception(res);
                        }
                        else
                            //adjust qty, set product.qty = sum(product details)
                            Products.SyncProductQty(invoiceDetails.SaleItems.ProductID);

                        invoiceDetails.SaleItems.MoveNext();
                    }

                    //step7:update Products Sold Quantity
                    invoiceDetails.SaleItems.Rewind();
                    invoiceDetails.SaleItems.Filter = InvoiceDetails.ColumnNames.ItemType + "=" + ((int)(Invoices.InvoiceCategories.Sale)).ToString();
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        //adjust soldqty, set product.soldqty += qty
                        Products.UpdateProductSoldQty(invoiceDetails.SaleItems.ProductID, invoiceDetails.SaleItems.Quantity);
                        invoiceDetails.SaleItems.MoveNext();
                    }
                }

                invoiceDetails.SaleItems.Filter = InvoiceDetails.ColumnNames.ItemType + "=" + ((int)(Invoices.InvoiceCategories.Repair)).ToString();
                if (invoiceDetails.SaleItems.RowCount > 0)
                {
                    //step3:add InvoiceDetails
                    InvoiceDetails ivcDetails = new InvoiceDetails();
                    invoiceDetails.SaleItems.Rewind();
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        ivcDetails.AddNew();
                        ivcDetails.BranchID = Branches.CurrentBranchID;
                        String desc = invoiceDetails.SaleItems.Description;
                        ivcDetails.AddInfo(invoice.ID, invoiceDetails.SaleItems.IMEI, invoiceDetails.SaleItems.Quantity,
                            invoiceDetails.SaleItems.GST, invoiceDetails.SaleItems.UnitPrice, invoiceDetails.SaleItems.Discount, invoiceDetails.SaleItems.Cost, desc);
                        ivcDetails.LastModifiedByUser = SessionUser.ID;
                        ivcDetails.s_ItemType = ((byte)Invoices.InvoiceCategories.Repair).ToString();
                        invoiceDetails.SaleItems.MoveNext();
                    }
                    ivcDetails.Save();

                    //step4: update repair status 
                    //temporarily store Repair grid using ProductID
                    string strBoxs = "";
                    ivcDetails.Rewind();
                    invoiceDetails.SaleItems.Rewind();
                    for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                    {
                        RepairJob jb = new RepairJob();
                        jb.LoadByPrimaryKey(invoiceDetails.SaleItems.ProductID);
                        if (jb.StatusID == RepairStatus.Returned)
                            throw new Exception(string.Format("Repair Job R{0} has been booked out before!", jb.RepairNo));
                        jb.PreviousStatusID = jb.StatusID;
                        jb.StatusID = RepairStatus.Returned;
                        jb.LastModifiedByUser = SessionUser.ID;
                        jb.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        jb.InvoiceID = invoice.ID;
                        jb.InvoiceDetailID = ivcDetails.ID;
                        jb.BranchID = Branches.CurrentBranchID;
                        if (jb.s_LoanPhoneID != "")
                        {
                            LoanPhones lp = LoanPhones.GetLoanPhoneById(jb.LoanPhoneID);
                            if (lp.RowCount > 0)
                            {
                                lp.Free = true;
                                lp.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                                lp.Save();

                                jb.LoanPhoneReturn = true;
                            }
                        }

                        jb.Save();

                        if (strBoxs.IndexOf(jb.s_RepairBoxID + ",") < 0)
                            strBoxs += jb.s_RepairBoxID + ",";

                        RepairStatusHistories hist = new RepairStatusHistories();
                        hist.AddNew();
                        hist.BranchID = Branches.CurrentBranchID;
                        hist.RepairJobID = jb.ID;
                        hist.RepairStatusID = RepairStatus.Returned;
                        hist.UpdatedByUser = SessionUser.ID;
                        hist.UpdatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        hist.Save();

                        invoiceDetails.SaleItems.MoveNext();
                        ivcDetails.MoveNext();
                    }

                    string[] boxIDs = strBoxs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < boxIDs.Length; i++)
                    {
                        View_RepairJobs.UpdateRepairBoxStatus(int.Parse(boxIDs[i]));
                    }
                }
                invoiceDetails.SaleItems.Filter = oldFilter;
                tx.CommitTransaction();

                ShowHintMessage(mainPanel, String.Format("(*) Invoice {0} has been created successfully!", txtInvoiceNo.Text));
                hidNewInvoiceID.Value = invoice.ID.ToString();
                invoiceDetails.Refresh();
                btnSubmit.Visible = false;
                btnPrint.Visible = true;

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "window.returnValue=1;", true);

                if(chkAutoPrint.Checked)
                    PrintInvoice();
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                if (oldFilter != "")
                    invoiceDetails.SaleItems.Filter = oldFilter;
                ShowErrorMessage(mainPanel, "(*) Error: " + ex.Message);
                ErrorLog.WriteToFile("SalesCtrl.ascx.cs", "btnSubmit_OnClick", ex.StackTrace);
            }
        }

        protected void btnNewInvoice_OnClick(object sender, EventArgs e)
        {
            NewInvoice();
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return this.ResolveClientUrl("~/EditPages/PrintHandler.aspx?key=" + PrintKey);
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintInvoice();
        }

        private void PrintInvoice()
        {
            try
            {
                InvoiceViewerCtrl ivcViewer = (InvoiceViewerCtrl)LoadControl(@"~/Controls/POSControls/InvoiceViewerCtrl.ascx");
                if (hidNewInvoiceID.Value != "")
                    ivcViewer.LoadInvoiceByID(int.Parse(hidNewInvoiceID.Value));

                Session[PrintKey] = ivcViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("SalesCtrl.ascx.cs", "PrintInvoice", ex.StackTrace);
            }
        }
    }
}